//定义影院相关的接口
const express = require('express')
const router = express.Router()
const response = require('../pool/Response')
//引入mysql连接池
const pool = require('../pool/pool')
//引入joi模块
const joi = require('joi')
const SECRET_KEY = 'JWT_SECRET_KEY'
const jwt = require('jsonwebtoken')

router.post('/user/login',(req,res) => {
    let {username,password} = req.body
    //表单验证
    let schema = joi.object({
        username:joi.string().required(),
        password:joi.string().required(),
    })
    let {error,value} =schema.validate(req.body)
    if(error){
        res.send(response.error(400,error))
        return
    }
    pool.query('select * from admin where username=? and password=?',[username,password],(error,result)=>{
        if(error){
            res.send(500,response.error(error))
        }
        if(result.length == 0 ){
         res.send(response.error(1001,'账号密码输入错误'))
        }else{
            //获取登录用户对象
            let user = result[0]
            //为该用户颁发一个token，未来该用户若做发送其他请求，则需要在请求头中Header中携带token，完成状态管理
           let payload = {id:user.id,nickname:user.nickname}
            let token = jwt.sign(payload,SECRET_KEY,{expiresIn:'1d'})
            user.password = undefined
            res.send(response.ok({user,token}))
        } 
    })
})
module.exports = router